import os
import zipfile
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.http import HttpResponse
from shutil import copyfile


def upload_exe(file, details):
    file_path = 'tmp/exe_zip_files/' + details['filename'] + '.zip'
    file_destination_dir = '/home/ubuntu/hydra-exe-packages/'
    file_dest = file_destination_dir + details['filename'] + '.zip'

    my_path = os.path.abspath(file_path)
    default_storage.save(my_path, ContentFile(file.read()))

    if os.path.exists(file_path):
        if os.path.isdir(file_destination_dir):
            copyfile(file_path, file_dest)
            if os.path.exists(file_dest):
                os.remove(file_path)
        else:
            os.mkdir(file_destination_dir)
            copyfile(file_path, file_dest)
            if(os.path.exists(file_dest)
               and os.path.exists(file_path)):
                os.remove(file_path)
    return 'success'


def download_exe(path):
    file_path = '/home/ubuntu/hydra-exe-packages/' + path + '.zip'
    my_path = os.path.abspath(file_path)
    file_open = open(my_path, "rb")
    response = HttpResponse(file_open, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename="' + path + '.zip"'
    return response
